package com.zqs.takeredpackage.util;


import com.zqs.takeredpackage.entity.RedPackage;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class RandomMoneyUtil {
    public static BigDecimal getRandomMoney(RedPackage _redPackage) {
        // remainSize 剩余的红包数量
        // remainMoney 剩余的钱
        if (_redPackage.getRemainSize() == 1) {
            _redPackage.setRemainSize(_redPackage.getRemainSize()-1);
            BigDecimal lastMoney = _redPackage.getRemainMoney().setScale(2, RoundingMode.DOWN);
            _redPackage.setRemainMoney(BigDecimal.ZERO);
            return lastMoney;
        }

        BigDecimal random = BigDecimal.valueOf(Math.random());
        BigDecimal min = BigDecimal.valueOf(0.01);

        BigDecimal halfRemainSize = BigDecimal.valueOf(_redPackage.getRemainSize()).divide(new BigDecimal(2), RoundingMode.UP);
        BigDecimal max1 = _redPackage.getRemainMoney().divide(halfRemainSize, RoundingMode.DOWN);
        BigDecimal minRemainAmount = min.multiply(BigDecimal.valueOf(_redPackage.getRemainSize() - 1)).setScale(2, RoundingMode.DOWN);
        BigDecimal max2 = _redPackage.getRemainMoney().subtract(minRemainAmount);
        BigDecimal max = (max1.compareTo(max2) < 0) ? max1 : max2;

        BigDecimal money = random.multiply(max).setScale(2, RoundingMode.DOWN);
        money = money.compareTo(min) < 0 ? min : money;

        _redPackage.setRemainSize(_redPackage.getRemainSize()-1);
        _redPackage.setRemainMoney(_redPackage.getRemainMoney().subtract(money).setScale(2, RoundingMode.DOWN));
        return money;
    }
}
